package service.impl;

import bean.UserBean;
import dao.IRecordDAO;
import dao.IUserDAO;
import dao.impl.RecordDAOImpl;
import dao.impl.UserDAOImpl;
import service.IUserService;

import java.time.LocalDate;

public class UserServiceImpl implements IUserService {
    private IUserDAO userDAO = new UserDAOImpl();
    private IRecordDAO recordDAO = new RecordDAOImpl();
    @Override
    public UserBean login(String username, String pwd) {
        return userDAO.login(username, pwd);
    }

    @Override
    public void save(int id, double money) {
        UserBean user = userDAO.getUserById(id);
        user.setMoney(user.getMoney() + money);
        userDAO.update(id, user.getMoney());
        recordDAO.insert(id, "存入" + money + "元", money, LocalDate.now());
    }

    @Override
    public boolean get(int id, Double money) {
        UserBean user = userDAO.getUserById(id);
        if (user.getMoney() < money) {
            return false;
        }
        user.setMoney(user.getMoney() - money);
        userDAO.update(id, user.getMoney());
        recordDAO.insert(id, "取出" + money + "元", money, LocalDate.now());
        return true;
    }

    @Override
    public UserBean query(int id) {
        return userDAO.getUserById(id);
    }

    @Override
    public String trans(int id, String name, Double money) {
        UserBean user = userDAO.getUserById(id);
        UserBean ortheruser = userDAO.getUserName(name);
        // 判断账号是否存在
        if (ortheruser == null) {
            return "查无此人";
        }
        // 判断是否转给自己
        if (user.getName().equals(name)) {
            return "不能转给自己";
        }
        // 判断余额是否足够
        if (money > user.getMoney()) {
            return "余额不足";
        }
        // 当期账户扣钱
        user.setMoney(user.getMoney() - money);
        userDAO.update(user.getId(), user.getMoney());
        recordDAO.insert(user.getId(), "向" + name + "转账" + money + "元", money, LocalDate.now());
        // 对方账户加钱
        ortheruser.setMoney(ortheruser.getMoney() + user.getMoney());
        userDAO.update(ortheruser.getId(), money);
        recordDAO.insert(ortheruser.getId(), "转入" + money + "元", money, LocalDate.now());
        return "转账成功";
    }
}
